from flask import Flask, Response, render_template, jsonify
import os
import subprocess
from camserver import scan_cameras, get_camera_details, generate_frames, capture_image, set_camera, close_camera

app = Flask(__name__)
PORT = 5000
@app.route('/')
def index():
    """渲染主页面"""
    return render_template('index.html')

@app.route('/scan_cameras', methods=['GET'])
def get_available_cameras():
    """返回可用的摄像头列表"""
    cameras = scan_cameras()
    return jsonify(cameras)

@app.route('/camera_details/<int:camera_index>', methods=['GET'])
def camera_details(camera_index):
    """返回指定摄像头的详细信息"""
    details = get_camera_details(camera_index)
    return jsonify(details)

@app.route('/capture', methods=['GET'])
def capture():
    """捕获当前摄像头的一帧图像"""
    return capture_image()

@app.route('/video_feed')
def video_feed():
    """提供实时视频流"""
    from camserver import current_camera_index  # 修复未定义错误
    return Response(generate_frames(current_camera_index),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/set_camera/<int:camera_index>', methods=['POST'])
def set_camera_route(camera_index):
    """设置当前使用的摄像头"""
    if camera_index is None or camera_index < 0:
        return jsonify({"error": "Invalid camera index"}), 400
    return set_camera(camera_index)

@app.route('/close_camera', methods=['POST'])
def close_camera_route():
    """关闭当前摄像头"""
    return close_camera()

if __name__ == '__main__':
    try:
        app.run(host='0.0.0.0', port=PORT)
    finally:
        close_camera()